import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import { clearShopCartStorage, formatGoodsList, isDockingEvent, setTabBarIndex } from '../../utils/hooks';
import {
  arrToTwoArr,
  compareTime,
  connectWifi,
  debounce,
  formatDateString,
  getElement,
  initLocationPersmiss,
  judgeAuth,
  openAuth
} from '../../utils/util';
import { setWatcher } from '../../utils/watch';
const $api = require('../../request/api').API;
const app = getApp();
Page({
  data: {
    menuBtnHeight: app.globalData.menuBtnHeight,
    menuBtnTop: app.globalData.menuBtnTop,
    menuBtnBottom: app.globalData.menuBtnBottom,
    menuBtnLeft: app.globalData.menuBtnLeft - 2,
    fixedTopHeight: 100, // 这个高度是呼叫器和顶部导航和状态栏的高渡
    beeperList: [], //所有的呼叫器列表
    twoBeeperList: [], //页面显示的两个呼叫器
    searchBeeperList: [], //搜索出来的呼叫器列表
    beeperId: '', //默认选中周边服务呼叫器，这里自定义为-1
    beeperType: '',
    beeperVersion: '',
    beeperName: '',
    btnLineNum: '',
    btnVoiceFlag: true,
    bgColor: 'var(--bg-color)',
    showLevel: -1, // 0表示显示精选全部，其它的数据表示只有精选，周边服务没有精选和全部，用-1表示
    addressType: '', //地址类型，如果是3表示结算的时候需要定位
    defaultOpen: 1, //1 是精选，2是全部
    btnId: '',
    btnType: '',
    btnServerClassifyIds: '',
    btnList: [], // 按键列表
    btnStyle: 0, // 精选是否是否新的页面样式 1表示是
    btnModelRelations: [], // 按键列表
    startPositionX: '', //滑动触屏开始的clientX位置
    startPositionY: '', //滑动触屏开始的clientY位置
    //通过定位或者选中的呼叫器
    latitude: '',
    longitude: '',
    address: '', //当前定位的地址
    provinceName: '', //省
    cityName: '', //市
    areaName: '', //区
    scrollLeft: 0, //坐滚动的距离
    refresh: false,
    showSearch: false,
    inputKey: '',
    scrollTop: 0,
    buyType: {},
    addressInfo: {}, //地址信息
    moduleType: 1, // 1表示旧的首页图，2表示新的首页设计图
    loading: false, // 按键加载中，true表示加载，false表示没加载
    noBtnList: false, // 没有服务按键
    bigImgUrl: '',
    showMergeBtn: false, // 合并弹框显示
    mergeBtns: [],
    showBindingPhone: false,
    deviceArrayShow: false, // 设备选择器弹窗显隐
    deviceArray: [], // 设备数组
    rescueInformation: undefined, // 救援信息
    localeId: '',
    openSearchName: ''
  },
  onLoad: async function ({ beeperId }) {
    beeperId &&
      this.setData({
        beeperId
      });
    this.init();
    app.eventBus.on('refreshBeeperList', this.handleRefreshBeeperList);
  },
  onUnload() {
    app.eventBus.off('refreshBeeperList', this.handleRefreshBeeperList);
  },
  onReady: function () {
    setWatcher(this);
  },
  onShow: async function () {
    setTabBarIndex(0);
    this.deleteGLobalDataBtnList();
    // 请求救援信息
    const { btnList, beeperId } = this.data;
    if (btnList.length > 0 && beeperId) {
      const activityTemplate = btnList.find(c => c.btnModuleType === 7);
      if (!activityTemplate) return;
      this.fetchRecentFirstAidOrderData(beeperId, activityTemplate.id);
    }
  },
  async handleRefreshBeeperList() {
    const res = await this.getBeeperList();
    const beeperList = res.data.data;
    if (beeperList.length > 0) {
      const {
        id,
        beeperType,
        defaultOpen,
        beeperVersion,
        addressType,
        showLevel,
        btnLineNum,
        btnVoiceFlag,
        btnStyle,
        bgColor,
        localeId
      } = beeperList[0];
      this.setData({
        beeperId: id,
        beeperType: beeperType ? beeperType : '',
        beeperVersion: beeperVersion ? beeperVersion : '',
        defaultOpen: id == -1 ? '' : showLevel > 0 ? showLevel : defaultOpen,
        addressType: id == -1 ? 3 : addressType,
        btnLineNum,
        btnVoiceFlag,
        showLevel,
        showSearch: false,
        btnStyle: id == -1 ? 0 : btnStyle,
        bgColor,
        localeId
      });
    }
    this.init();
  },
  // 页面初始化操作
  async init() {
    Toast.loading({
      message: '加载中',
      forbidClick: true,
      mask: true,
      duration: 0
    });
    try {
      let beeperId = this.data.beeperId || '';
      let res = await this.getBeeperList();
      let obj = {
        id: -1,
        name: '周边',
        beeperType: '',
        beeperVersion: '',
        defaultOpen: '',
        btnStyle: 0,
        addressType: 3,
        showLevel: -1,
        bgColor: ''
      };
      let beeperList = [obj].concat(res.data.data || []);
      let twoBeeperList = beeperList.slice(0, 2);
      let index = -1;
      beeperId && (index = beeperList.findIndex(item => item.id == beeperId));
      if (index !== -1 && beeperId !== -1) {
        // 如果呼叫器beeprId存在呼叫器是带参进入到该页面
        const {
          beeperType,
          defaultOpen,
          btnStyle,
          bgColor,
          beeperVersion,
          addressType,
          name,
          showLevel,
          btnVoiceFlag,
          btnLineNum,
          localeId
        } = beeperList[index];
        twoBeeperList.splice(1, 1, beeperList[index]);
        obj = {
          defaultOpen: showLevel > 0 ? showLevel : defaultOpen,
          btnStyle,
          bgColor,
          beeperId,
          beeperType,
          beeperVersion,
          addressType,
          beeperName: name,
          showLevel: showLevel,
          btnVoiceFlag,
          btnLineNum,
          localeId
        };
        this.setData({
          twoBeeperList,
          beeperList,
          ...obj
        });
        await this.getServerBtnList(1);
      } else if (beeperList.length > 1) {
        // 呼叫器列表有数据
        this.setData({
          twoBeeperList: beeperList.slice(0, 2),
          beeperList
        });
        await this.getServerBtnList(0);
      } else {
        // 呼叫器长度小于一直接选择周边
        obj = {
          beeperId: -1,
          defaultOpen: '',
          btnStyle: 0,
          bgColor: '',
          beeperVersion: '',
          beeperType: '',
          addressType: 3,
          beeperName: '周边',
          showLevel: -1,
          btnLineNum: 3,
          btnVoiceFlag: 1
        };
        this.setData({
          twoBeeperList,
          beeperList,
          ...obj
        });
        await this.getServerBtnList(1);
      }
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 登陆后通过呼叫器获取按键
   * @param {*} query 0表示查呼叫器 1表示不查呼叫器
   */
  async getServerBtnList(query = 0) {
    const {
      beeperId,
      address,
      defaultOpen,
      latitude,
      longitude,
      provinceName,
      cityName,
      areaName,
      beeperType,
      beeperVersion,
      twoBeeperList,
      localeId
    } = this.data;
    if (beeperId == -1 && !address) {
      let val = null;
      val = await judgeAuth('scope.userLocation');
      if (val) {
        await this.getLocationInfo();
      }
    }
    let params = {
      beeperId: beeperId == -1 ? '' : beeperId,
      query, //1表示不查呼叫器,0表示查
      type: defaultOpen,
      latitude,
      longitude,
      provinceName,
      cityName,
      areaName,
      beeperType,
      beeperVersion
    };
    this.setData({
      btnList: [],
      btnModelRelations: [],
      bigImgUrl: ''
    });
    try {
      Toast.loading({
        duration: 0,
        forbidClick: true,
        message: '加载中'
      });
      const res = await $api.serverBtnList(params);
      let { btnList, btnModelRelations } = res.data.data;
      btnList = btnList || [];
      btnList.forEach(item => {
        item.value = item.value + '?time=' + new Date().getTime();
        // 如果按钮里面有产品的话就计算产品活动 计算活动
        item.btnListVos && formatGoodsList(item.btnListVos);
        // 通过事件来判断是不是对接，如果是添加一个属性dockingFlag = 2
        isDockingEvent(item.eventId) && (item.dockingFlag = 2);
      });

      // 如果按键列表中有包含动态模版显示动态模版样式 同时请求急救信息
      const activityTemplate = btnList.find(c => c.btnModuleType === 7);
      if (activityTemplate && res.data.data.btnModelParam) {
        const { beeperId } = res.data.data;
        this.fetchRecentFirstAidOrderData(beeperId || this.data.beeperId, activityTemplate.id);
      }
      btnModelRelations = btnModelRelations || [];
      this.setData({
        noBtnList: btnList.length ? false : true
      });
      if (!query) {
        // query为0表示查询呼叫器
        const data2 = res.data.data;
        const obj = {
          beeperId: data2.beeperId || -1,
          beeperType: data2.beeperType || '',
          beeperVersion: data2.beeperVersion || '',
          defaultOpen: data2.beeperId ? (data2.showLevel > 0 ? data2.showLevel : data2.defaultOpen) : '',
          addressType: data2.beeperId ? data2.addressType : 3,
          beeperName: data2.name,
          showLevel: data2.showLevel,
          btnVoiceFlag: data2.btnVoiceFlag,
          btnLineNum: data2.btnLineNum,
          btnStyle: data2.btnStyle,
          bgColor: data2.bgColor,
          localeId: data2.localeId
        };
        this.setData(obj);
        if (obj.beeperId !== -1) {
          twoBeeperList.splice(1, 1, obj);
          twoBeeperList[1].id = obj.beeperId;
          twoBeeperList[1].name = obj.beeperName;
          this.setData({
            twoBeeperList
          });
        }
      }
      this.formatBtnList(btnList, btnModelRelations);
    } finally {
      Toast.clear();
      this.setData({
        refresh: false
      });
      wx.pageScrollTo({
        scrollTop: 0
      });
      this.calcHeight();
    }
  },

  // 获取定位信息
  async getLocationInfo() {
    const res = await initLocationPersmiss();
    this.setData({
      latitude: res.location.lat,
      longitude: res.location.lng,
      address: res.address_component.city,
      provinceName: res.address_component.province,
      cityName: res.address_component.city,
      areaName: res.address_component.district
    });
  },

  // 计算顶部高度
  calcHeight() {
    setTimeout(() => {
      wx.nextTick(async () => {
        let res = await getElement('.fixed-wrapper');
        this.setData({
          fixedTopHeight: res[0].height
        });
      });
    });
  },

  // 上面的大图加载完毕还得重新计算一下顶部定位的高度高度
  imgLoadingEnd() {
    // 图片已经加载完成但是并没有渲染到页面上去
    setTimeout(() => {
      this.calcHeight();
    }, 40);
  },

  // 获取呼叫器数据
  async getBeeperList(params) {
    return (
      (await $api.beeperList({
        type: 2,
        ...params
      })) || []
    );
  },

  // 把按键放到模块里面去
  formatBtnList(btnList, btnModelRelations) {
    let { btnStyle, defaultOpen, bigImgUrl } = this.data;
    bigImgUrl = '';
    const filterBtnList = btnList.filter(item => !item.parentBtnCode);
    if (btnStyle == 1 && defaultOpen == 1) {
      btnModelRelations.forEach((item, index) => {
        if (item.moduleType == 1 && item.btnFormats.length) {
          item.btnFormats.forEach((item2, index) => {
            item2.list = arrToTwoArr(
              filterBtnList.filter(
                item3 => item3.formatCode == item2.formatCode && item3.moduleCode == item.moduleCode
              ),
              item2.row * item2.col
            );
            item2.currentIndex = 0;
          });
        } else if (item.moduleType == 2) {
          item.list = filterBtnList.filter(item2 => item2.moduleCode == item.moduleCode);
        } else if (item.moduleType == 3) {
          item.list = arrToTwoArr(
            filterBtnList.filter(item2 => item2.moduleCode == item.moduleCode),
            3
          );
        } else if (item.moduleType == 4) {
          item.list = filterBtnList.find(item2 => item2.moduleCode == item.moduleCode);
        } else if (item.moduleType == 5 && index == 0) {
          bigImgUrl = item.bigImgUrl;
        } else if (item.moduleType == 6) {
          item.list = filterBtnList.find(item2 => item2.moduleCode == item.moduleCode);
        }
      });
      btnModelRelations[0].moduleType == 5 && btnModelRelations.shift();
    }
    let _btnModelRelations = btnModelRelations;

    //  搜索模块 推荐产品模块没有对应按键 模版中不渲染
    if (!btnList.find(c => c.btnModuleType === 6))
      _btnModelRelations = _btnModelRelations.filter(c => c.moduleType !== 6);
    if (!btnList.find(c => c.btnModuleType === 3))
      _btnModelRelations = _btnModelRelations.filter(c => c.moduleType !== 3);
    if (!btnList.find(c => c.btnModuleType === 4))
      _btnModelRelations = _btnModelRelations.filter(c => c.moduleType !== 4);
    this.setData({
      btnList,
      btnModelRelations: _btnModelRelations,
      bigImgUrl
    });
  },

  /**
   * 页面的初始数据
   */
  handleSwiperItemChange({ currentTarget, detail }) {
    /*
     * currentTarget.dataset.index 第一个是两个索引结合起来的 1-1,第一个表示第几个模块，第二个表示该
     * 模块下的第几个swiper,detail上面的索引才是swiper-item的索引
     */
    let { index } = currentTarget.dataset;
    // const { btnModelRelations } = this.data
    index = index.split('-').map(item => Number(item));
    let prop = `btnModelRelations[${index[0]}].btnFormats[${index[1]}].currentIndex`;
    // btnModelRelations[index[0]].btnFormats[index[1]].currentIndex = detail.current
    this.setData({
      [prop]: detail.current
    });
  },

  // 去产品详情
  toGoodsDetail(e) {
    const { item, open, goods } = e.currentTarget.dataset;
    const { goodsId, id, specDisplayType } = goods;
    if (specDisplayType == 1) {
      // 跳转到规格页面
      wx.navigateTo({
        url: '/subcontract/home/pages/goodsSpec/index?goodsId=' + goodsId
      });
      return;
    }
    // 先清空购物车
    // clearShopCartStorage();
    const query = `goodsId=${goodsId}&beeperBtnId=${id}${open ? '&open=true' : ''}`;
    this.toUrl(item, `/subcontract/home/pages/goodsDetail/index?${query}`);
  },

  // 点击获取更多信息
  async getMoreInfo() {
    let val = null;
    val = await judgeAuth('scope.userLocation');
    if (val === false) {
      val = await openAuth('scope.userLocation');
      if (val) {
        await this.getLocationInfo();
      }
    } else {
      await this.getLocationInfo();
    }
    this.getServerBtnList(1);
  },

  // 点击搜索
  async handleClickSearch() {
    const { showSearch } = this.data;
    this.setData({
      showSearch: !showSearch,
      inputKey: ''
    });
    const res = await this.getBeeperList();
    this.setData({
      searchBeeperList: res.data.data || [],
      scrollTop: 0
    });
  },

  //呼叫器开放搜索
  openSearchInput(e) {
    const type = e.currentTarget.dataset.type;
    const val = e.detail;
    if (type == 1) {
      this.setData({
        openSearchName: val
      });
    } else {
      if (!this.data.openSearchName) {
        Toast('请输入呼叫器名称');
        return false;
      }
      wx.navigateTo({
        url: '../../subcontract/home/pages/openSearch/index?name=' + this.data.openSearchName
      });
    }
  },

  //搜索
  handleInputSearch: debounce(async function (e) {
    const res = await this.getBeeperList({
      value: e.detail
    });
    this.setData({
      searchBeeperList: res.data.data || []
    });
  }, 500),

  // 点击遮罩层
  handleCloseSearch() {
    this.setData({
      showSearch: false
    });
  },

  // 长按录音
  recordSound(e) {
    const { item } = e.currentTarget.dataset;
    if (!(item.relationType == 1 && (item.eventId == 10 || item.dockingFlag))) return;
    this.pageX = e.changedTouches[0].pageX;
    this.pageY = e.changedTouches[0].pageY;
    this.setData({
      btnId: item.id,
      btnType: item.btnType,
      btnServerClassifyIds: item.classifyIds
    });
    if (!item.voiceOrderFlag) return;
    this.timer = setTimeout(() => {
      clearTimeout(this.timer);
      this.timer = null;
      this.selectComponent('#sound-record-two').start();
    }, 900);
  },

  // 松开结束录音
  endSound(e) {
    const { relationType, eventId, dockingFlag, voiceOrderFlag } = e.currentTarget.dataset.item;
    if (!(relationType == 1 && (eventId == 10 || dockingFlag))) return;
    if (this.timer || !voiceOrderFlag) {
      clearTimeout(this.timer);
      this.timer = null;
      // 防止点击多次
      if (!this.forbid) {
        const { pageX, pageY } = e.changedTouches[0];
        if (Math.abs(this.pageX - pageX) < 2 && Math.abs(this.pageY - pageY) < 2) {
          this.toGoodsList(e);
        }
        this.forbid = true;
      }
      setTimeout(() => {
        this.forbid = false;
      }, 800);
    } else {
      this.selectComponent('#sound-record-two').end();
    }
  },

  // 提示录制声音
  tipRecordSound(e) {
    Dialog.alert({
      title: '提示',
      message: '长按可以录音',
      closeOnClickOverlay: 'true'
    }).then(() => {});
    let index = e.currentTarget.dataset.index;
    this.data.btnList[index].tip = false;
    this.setData({
      btnList: this.data.btnList
    });
  },

  // 选择呼叫器
  async selectBeeper(e) {
    const { item, search } = e.target.dataset;
    if (!item) return;
    const { twoBeeperList } = this.data;
    const {
      id,
      beeperType,
      defaultOpen,
      beeperVersion,
      addressType,
      showLevel,
      btnLineNum,
      btnVoiceFlag,
      btnStyle,
      bgColor,
      localeId
    } = item;
    if (id) {
      if (search) {
        twoBeeperList.splice(1, 1, item);
      }
      this.setData({
        beeperId: id,
        beeperType: beeperType ? beeperType : '',
        beeperVersion: beeperVersion ? beeperVersion : '',
        defaultOpen: id == -1 ? '' : showLevel > 0 ? showLevel : defaultOpen,
        addressType: id == -1 ? 3 : addressType,
        btnLineNum,
        btnVoiceFlag,
        twoBeeperList,
        showLevel,
        showSearch: false,
        btnStyle: id == -1 ? 0 : btnStyle,
        bgColor,
        localeId
      });
    }
    await this.getServerBtnList(1);
  },

  // 选择按钮分类
  async selectBtnType(e) {
    const defaultOpen = e.detail.name;
    this.setData({
      defaultOpen
    });
    await this.getServerBtnList(1);
  },

  // 获取该呼叫器的地址信息
  getAddress() {},

  // 选择位置
  async toSelectLocation() {
    const res = await judgeAuth('scope.userLocation');
    if (res) {
      if (this.data.address) {
        wx.navigateTo({
          url:
            '/subcontract/home/pages/selectLocation/index?address=' +
            this.data.address +
            '&province=' +
            this.data.provinceName
        });
      } else {
        wx.navigateTo({
          url: '/subcontract/home/pages/selectLocation/index'
        });
      }
    } else {
      await this.getLocationInfo();
      if (this.data.beeperId == -1) {
        this.getServerBtnList(1);
      }
    }
  },

  // 刷新呼叫器
  refreshBeeper() {
    this.setData({
      refresh: true
    });
    // app.globalData.selectBeeperId = true
    this.onLoad({});
  },

  // 去商品列表页面
  toGoodsList(e) {
    const { item } = e.currentTarget.dataset;
    if (this.clickOutTime(item.serverTimeRange)) return;
    // 这里用一个异步，确保触屏后forbidToGoodsList要先获取到
    Promise.resolve().then(() => {
      if (this.forbidToGoodsList) {
        return;
      }
      this.toUrl(item, '/subcontract/home/pages/goodsList/index');
    });
  },

  handleSearchGoods(e) {
    this.searchGoodsKey = e.detail;
  },

  //跳转,把改页面的参数全局保存，因为后面的页面需要用到
  toUrl(obj, url) {
    const { id, classifyIds, btnType, linkUrl, eventId } = obj;
    let { beeperId, latitude, longitude, provinceName, cityName, areaName, defaultOpen, addressType } = this.data;
    beeperId = beeperId == -1 ? '' : beeperId;
    app.globalData['btnList.beeperId'] = beeperId;
    app.globalData['btnList.latitude'] = latitude;
    app.globalData['btnList.longitude'] = longitude;
    app.globalData['btnList.provinceName'] = provinceName;
    app.globalData['btnList.cityName'] = cityName;
    app.globalData['btnList.areaName'] = areaName;
    app.globalData['btnList.btnId'] = id;
    app.globalData['btnList.btnServerClassifyIds'] = classifyIds;
    app.globalData['btnList.queryType'] = defaultOpen;
    app.globalData['btnList.btnType'] = btnType;
    app.globalData['btnList.addressType'] = addressType;
    app.globalData['btnList.linkUrl'] = linkUrl;
    app.globalData['btnList.eventId'] = eventId;
    wx.navigateTo({
      url
    });
  },

  // 清空全局数据app.globalData["btnList.*"]
  deleteGLobalDataBtnList() {
    delete app.globalData['btnList.beeperId'];
    delete app.globalData['btnList.latitude'];
    delete app.globalData['btnList.longitude'];
    delete app.globalData['btnList.provinceName'];
    delete app.globalData['btnList.cityName'];
    delete app.globalData['btnList.areaName'];
    delete app.globalData['btnList.btnId'];
    delete app.globalData['btnList.btnServerClassifyIds'];
    delete app.globalData['btnList.queryType'];
    delete app.globalData['btnList.btnType'];
    delete app.globalData['btnList.addressType'];
    delete app.globalData['btnList.linkUrl'];
    delete app.globalData['btnList.eventId'];
    delete app.globalData['dock.date'];
    delete app.globalData['dock.doctorId'];
    delete app.globalData['dock.patientId'];
    delete app.globalData['dock.timerinterval'];
    delete app.globalData['btnList.variantId'];
  },

  // 处理事件按钮事件
  handleBtnEvent(e) {},

  // 其它事件
  async otherEvent(e) {
    const { item, moduletype } = e.currentTarget.dataset;
    // 条件判断能不能继续往下执行
    if (moduletype === 6) {
      this.toUrl(item, `/subcontract/home/pages/goodsSearch/index?keyword=${this.searchGoodsKey || ''}`);
      return;
    }
    const { relationType, eventId, linkUrl, id, dockingFlag, btnCode, serverTimeRange } = item;
    if (this.clickOutTime(serverTimeRange)) return;
    if (relationType == 1 && (eventId == 10 || dockingFlag)) return;
    let { beeperId, buyType, defaultOpen, addressType, btnList } = this.data;

    // 关联类型switch
    switch (relationType) {
      case 1:
        Toast.loading({
          message: '正在加载中',
          forbidClick: true,
          mask: true
        });
        const res = await $api.getBtnDefaultGoods({
          beeperId,
          btnId: id
        });
        const { goods, nums, attr, addressInfo } = res.data.data;
        if (eventId == 13 || eventId == 14) clearShopCartStorage();
        buyType = {
          ...item,
          eventId,
          beeperId,
          linkUrl,
          queryType: defaultOpen,
          attr
        };
        buyType.goods = {
          ...goods,
          nums
        };
        buyType.addressInfo = {
          ...addressInfo,
          addressType
        };
        this.setData({
          buyType
        });
        Toast.clear();
        break;
      case 2:
        wx.navigateTo({
          url: '/subcontract/person/pages/index?url=' + linkUrl
        });
        break;
      case 3:
        const arr = item.linkUrl.split(',');
        let params = null;
        if (arr.length > 1) {
          params = {
            path: arr[1],
            appId: arr[0]
          };
        } else {
          params = {
            shortLink: item.linkUrl
          };
        }
        wx.navigateToMiniProgram({
          ...params,
          success(res) {
            // 打开成功
          }
        });
        break;
      case 4:
        if (eventId == 1) {
          const res = await $api.getWifiInfo({
            beeperId
          });
          const { wifiName, wifiPwd } = res.data.data;
          connectWifi(wifiName, wifiPwd);
        } else if (eventId == 2) {
          // 拨打电话
          wx.makePhoneCall({
            phoneNumber: linkUrl //仅为示例，并非真实的电话号码
          });
        } else if (eventId == 6) {
          // eventId为6表示合并按键的选项
          this.setData({
            mergeBtns: btnList.filter(item => item.parentBtnCode == btnCode),
            showMergeBtn: true
          });
        } else if (eventId == 51) {
          this.btnId = id;
          this.outHospital();
          // phone = wx.getStorageSync(Storage.PHONE)
          // if(!phone) return
          // await Dialog.confirm({
          //   title:"提示",
          //   message:"确定出院"
          // })
          // app.globalData.beeperId = ?
          // this.onShow()
        }
        break;
      case 5:
        switch (eventId) {
          case 3:
            this.toUrl(item, '/subcontract/home/pages/consult/index');
            break;
          case 4:
            this.toUrl(item, '/subcontract/home/pages/chat/chat');
            break;
          case 5:
            this.toUrl(item, '/subcontract/home/pages/activity/index');
            break;
          case 7:
            wx.navigateTo({
              url:
                '/subcontract/home/pages/propertyNotice/index?beeperId=' +
                beeperId +
                '&parentIds=' +
                (linkUrl || '') +
                '&btnId=' +
                item.id
            });
            break;
          case 53:
            wx.navigateTo({
              url: '/subcontract/home/pages/healthPoints/index'
            });
            break;
          case 54:
            this.toUrl(item, '/subcontract/home/pages/consultDetail/index?id=' + linkUrl);
            break;
          case 55: // 事件类型为设备详情
            const params = {
              beeperId,
              btnId: item.id
            };
            $api.BeeperBtnListSafety(params).then(res => {
              const { data } = res.data;
              if (!data || data.length === 0) {
                Toast.fail('该分类下没有绑定设备');
              } else if (data.length === 1) {
                this.handleEquipmentTypeSwitch(data[0].id, Number(item.linkUrl));
              } else {
                this.setData({
                  deviceArray: data,
                  deviceArrayShow: true,
                  selectDeviceType: linkUrl
                });
              }
            });
            break;
          case 57:
            this.toUrl(
              item,
              '/subcontract/home/pages/noticeDetail/index?identity=' + linkUrl + '&beeperId=' + beeperId
            );
            break;
          case 58:
            wx.navigateTo({
              url: '/subcontract/home/pages/reportingSituation/index?beeperId=' + beeperId
            });
            break;
          case 59:
            wx.navigateTo({
              url: '/subcontract/home/pages/fireReport/index?beeperId=' + beeperId
            });
            break;
          case 60:
            wx.navigateTo({
              url: '/subcontract/home/pages/propertyPayment/index?beeperId=' + beeperId + '&btnId=' + id
            });
            break;
          case 61:
            wx.navigateTo({
              url: '/subcontract/home/pages/fireDetection/index?beeperId=' + beeperId + '&btnId=' + id
            });
            break;
        }
        break;
    }
  },

  // 去外部链接或者其它页面
  toOtherUrl(e) {
    const { item } = e.currentTarget.dataset;
    if (item.relationType == 2) {
      wx.navigateTo({
        url: '/subcontract/person/pages/h5Page/index?url=' + encodeURIComponent(item.linkUrl)
      });
    } else if (item.relationType == 3) {
      wx.navigateToMiniProgram({
        shortLink: item.linkUrl,
        // appId:"wxc7e231d2c498bf7e",
        success(res) {
          // 打开成功
        }
      });
    } else if (item.relationType == 5) {
      this.toUrl(
        item,
        '/subcontract/home/pages/consult/index?beeperId=' + this.data.beeperId + '&classifyIds=' + item.classifyIds
      );
    }
  },

  // 触屏开始滑动
  silderStart(e) {
    if (this.data.showLevel > 0) return;
    this.setData({
      startPositionX: e.changedTouches[0].clientX,
      startPositionY: e.changedTouches[0].clientY
    });
  },

  // 触屏结束滑动
  silderEnd(e) {
    if (this.data.showLevel > 0) return;
    let endPositionX = e.changedTouches[0].clientX;
    let endPositionY = e.changedTouches[0].clientY;
    let tempX = endPositionX - this.data.startPositionX;
    let tempY = Math.abs(endPositionY - this.data.startPositionY);
    let defaultOpen = this.data.defaultOpen;
    if (tempX < -45 && defaultOpen == 1 && tempY < 25) {
      this.setData({
        // beeperId:beeperList[index+1].id
        defaultOpen: 2
      });
      this.getServerBtnList(1);
    }
    if (tempX > 45 && defaultOpen == 2 && tempY < 25) {
      this.setData({
        defaultOpen: 1
      });
      this.getServerBtnList(1);
    }
    // 触屏的范围，当触屏在一定范围之外就不会跳转详情页
    if (Math.abs(tempX) > 15 || tempY > 15) {
      this.forbidToGoodsList = true;
    } else {
      this.forbidToGoodsList = false;
    }
  },

  closeShowMergeBtn() {
    this.setData({
      showMergeBtn: false
    });
  },

  async confirmBindingPhone(e) {
    const { phone, code } = e.detail;
    const params = {
      phone,
      code
    };
    await $api.setUserPhone(params);
    Toast.success('绑定成功');
    this.closeBindingPpone();
    this.outHospital(false);
  },

  closeBindingPpone() {
    this.setData({
      showBindingPhone: false
    });
  },

  async outHospital(tip = true) {
    if (tip) {
      await Dialog.confirm({
        title: '提示',
        message: '确定一键出院'
      });
    }

    Toast.loading({
      duration: 0,
      message: '请稍等，处理中'
    });
    try {
      let res = await $api.btnEventAction({
        beeperId: this.data.beeperId,
        btnId: this.btnId
      });
      app.globalData.beeperId = res.data.data;
      this.onShow();
    } catch (err) {
      if (err.status == '412') {
        this.setData({
          showBindingPhone: true
        });
      }
    }
  },

  // 判断按键是否在时间外
  clickOutTime(serverTimeRange) {
    if (serverTimeRange) {
      serverTimeRange = serverTimeRange.split(',');
      const nowTime = formatDateString(new Date(), 'HH:ss');
      if (compareTime(serverTimeRange[0], serverTimeRange[1]) == 1) {
        // 开始时间要大，说明是间隔一天
        if (compareTime(nowTime, serverTimeRange[1]) == 1 && compareTime(nowTime, serverTimeRange[0]) == -1) {
          Toast.fail('不在时间内');
          return true;
        }
      } else {
        if (compareTime(nowTime, serverTimeRange[1]) == 1 || compareTime(nowTime, serverTimeRange[0]) == -1) {
          Toast.fail('不在时间内');
          return true;
        }
      }
      // const beginTime = compareTime(nowTime,serverTimeRange[1])
    }
  },

  // 设备选择change
  handledeviceSelectionConfirm(event) {
    const { index } = event.detail;
    const { deviceArray, selectDeviceType } = this.data;
    this.handleEquipmentTypeSwitch(deviceArray[index].id, Number(selectDeviceType));
    this.setData({
      deviceArrayShow: false,
      deviceArray: []
    });
  },

  // 设备选择关闭
  handledeviceSelectiCancel() {
    this.setData({
      deviceArrayShow: false,
      deviceArray: []
    });
  },

  // 急救模块图片预览
  handleFirstAidModuleImagePreview() {
    const { rescueInformation } = this.data;
    if (rescueInformation.siteUrl) {
      wx.previewImage({
        current: rescueInformation.siteUrl,
        urls: [rescueInformation.siteUrl]
      });
    }
  },

  /**
   * 前往设备详情
   * @param id
   * @param type
   */
  handleEquipmentTypeSwitch(id, type) {
    switch (type) {
      case 1:
        wx.navigateTo({
          url: '/subcontract/equipment/pages/details/index?beeperId=' + id
        });
        break;
      case 3:
        console.log('烟雾');
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsY/index?beeperId=' + id
        });
        break;
      case 4:
        console.log('燃气');
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsR/index?beeperId=' + id
        });
        break;
      case 5:
        console.log('门磁');
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsM/index?beeperId=' + id
        });
        break;
      case 6:
        console.log('水浸');
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsW/index?beeperId=' + id
        });
        break;
      case 8:
        console.log('SOS');
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsS/index?beeperId=' + id
        });
        break;
      case 9:
        console.log('跌倒');
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsD/index?beeperId=' + id
        });
        break;
      case 10:
        console.log('红外');
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsH/index?beeperId=' + id
        });
        break;
      case 11:
        console.log('睡眠监测仪');
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsL/index?beeperId=' + id
        });
        break;
      case 12:
        console.log('血糖仪');
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsG/index?beeperId=' + id + '&localeId=' + localeId
        });
        break;
      case 13:
        console.log('血压仪');
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsP/index?beeperId=' + id + '&localeId=' + localeId
        });
        break;
      case 14:
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsDP/index?beeperId=' + id + '&localeId=' + localeId
        });
        break;
      case 15:
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsSC/index?beeperId=' + id
        });
        break;
      case 16:
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsNB/index?beeperId=' + id
        });
        break;
      case 17:
        wx.navigateTo({
          url: '/subcontract/equipment/pages/detailsSW/index?beeperId=' + id
        });
        break;
      default:
        break;
    }
  },

  /**
   * 弹框显示急救活动模版的通知信息
   */
  handleNotificationClick() {
    const { rescueInformation } = this.data;
    if (rescueInformation) {
      Dialog.alert({
        title: '急救通知',
        message: `${rescueInformation.villageName}${rescueInformation.floorName}${rescueInformation.houseNumber}出现急救情况`
      });
    }
  },

  /**
   * 获取救援信息
   * @param beeperId
   * @param btnId
   */
  fetchRecentFirstAidOrderData(beeperId, btnId) {
    $api
      .GetRecentFirstAidOrder({
        beeperId,
        btnId
      })
      .then(res => {
        const { data } = res.data;
        if (data)
          this.setData({
            rescueInformation: data
          });
      });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    app.globalData.beeperOrderId = this.data.beeperId;
    app.globalData.localeId = this.data.localeId;
    app.globalData.beeperType = this.data.beeperType;
    this.closeShowMergeBtn();
  },

  onShareAppMessage: function () {},
  onShareTimeline: function () {}
});
